<template>
    <van-popup v-model:show="visible" position="bottom" :style="{ height: '100%' }" @open="openChange">

        <!-- 顶部按钮 -->
        <div class="dialogDiv-top">
            <div class="dialogDiv-top-left">
                <van-button class="dialogDiv-size" @click="handleClose">取消</van-button>
                <van-button class="dialogDiv-size" @click="cancelUsed('remove')" :disabled="disabledDisplay"
                    v-if="userType">取消常用</van-button>
            </div>
            <div class="dialogDiv-top-left">
                <van-button type='primary' class="dialogDiv-size dialogDiv-color" @click="cancelUsed('add')"
                    :disabled="disabledCheckbox" v-if="userType">设为常用</van-button>
                <van-button type='primary' class="dialogDiv-size dialogDiv-color" @click="handleConfirm">确定</van-button>
            </div>
        </div>

        <!-- 搜索 -->
        <div class="dialogDiv-search">
            <van-search v-model="inputSearch" placeholder="请输入搜索关键词" clearable @clear="clearSearch"
                style="width: 100%;" />
        </div>

        <div class="van-list" ref="topRef">

            <!-- 搜索结果 -->
            <div class="clearable-used" v-if="searchOutcome.length">
                <div class="clearable-used-list">
                    搜索结果：
                </div>

                <template v-for="item in searchOutcome" :key="item.id">
                    <van-checkbox-group v-model="contactsChecked" class="clearable-used-checkbox"
                        v-if="parameter === 'cc'">
                        <van-checkbox :name="item.id" style="margin-top: 15px;">
                            <div class="checkbox-name">
                                {{ item.name }}
                            </div>
                        </van-checkbox>
                    </van-checkbox-group>

                    <van-radio-group v-model="radioChecked" class="clearable-used-radio" v-else>
                        <van-radio :name="item.id">
                            <div class="checkbox-name">
                                {{ item.name }}
                            </div>
                        </van-radio>
                    </van-radio-group>
                </template>
            </div>

            <!-- 通讯录 -->
            <van-index-bar :index-list="indexList" :sticky="false" @select="handleSelect">

                <!-- 常用列表 -->
                <template v-if="contactsListData.length">
                    <van-index-anchor index="☆" style="background: #eee">
                        常用列表
                    </van-index-anchor>

                    <van-cell v-for="child in contactsListData" :key="child.name">
                        <template #title>
                            <van-checkbox-group v-model="contactsChecked" v-if="parameter === 'cc'">
                                <van-checkbox :name="child.id">
                                    <div class="checkbox-name">
                                        {{ child.name }}
                                    </div>
                                </van-checkbox>
                            </van-checkbox-group>

                            <van-radio-group v-model="radioChecked" v-else>
                                <van-radio :name="child.id">
                                    <div class="checkbox-name">
                                        {{ child.name }}
                                    </div>
                                </van-radio>
                            </van-radio-group>
                        </template>
                    </van-cell>
                </template>

                <div v-for="item in list" :key="item.name">
                    <van-index-anchor :index="item.name" style="background: #eee">{{
                        item.name
                        }}</van-index-anchor>

                    <van-cell v-for="child in item.children" :key="child.name">
                        <template #title>
                            <van-checkbox-group v-model="contactsChecked" v-if="parameter === 'cc'">
                                <van-checkbox :name="child.id">
                                    <div class="checkbox-name">
                                        {{ child.name }}
                                    </div>
                                </van-checkbox>
                            </van-checkbox-group>

                            <van-radio-group v-model="radioChecked" v-else>
                                <van-radio :name="child.id">
                                    <div class="checkbox-name">
                                        {{ child.name }}
                                    </div>
                                </van-radio>
                            </van-radio-group>
                        </template>
                    </van-cell>
                </div>
            </van-index-bar>

        </div>
    </van-popup>
</template>

<script setup lang='ts'>
import { contactsAddSave, getContactsList } from '@/api/worksheets';
import type { CommonlyType, ContactItemType } from '@/api/worksheets/type';

const prop = defineProps<{
    width?: number
    parameter: string //列表参数  to或者cc
    operate_type: string //操作类型  create:创建   transfer:工单流转
    customer_id?: null | number //客户id  创建工单，选择FAB的id  创建工单时必传
    ticket_number?: null | number //工单号  工单流转，工单流转时必传
    commonlyId?: string //单选 回显id
    // listId?: string //列表单选 回显id
    commonlyListId?: string[] //多选 回显id
    // listDataId?: string[] //列表多选 回显id
}>()

const emit = defineEmits<{
    (e: 'radioChange', val: CommonlyType): void//单选 选中数据事件
    (e: 'checkboxChange', val: CommonlyType[]): void//多选 选中数据事件
}>()

//控制弹窗显示隐藏
const visible = defineModel<boolean>('modelValue');

//1:CIE     0:普通用户
const userType = computed(() => {
    return Number(localStorage.getItem('mobile_userType'))
})

// 控制取消常用按钮是否禁用
const disabledDisplay = computed(() => {

    if (contactsListData.value.some(item => item.id === radioChecked.value) || contactsListData.value.some(i => contactsChecked.value.includes(i.id))) {
        return false
    } else {
        return true
    }
})

// 控制设为常用按钮是否禁用
const disabledCheckbox = computed(() => {

    if (list.value.flatMap(item => item.children).some(i => i.id === radioChecked.value) || list.value.flatMap(k => k.children).some(i => contactsChecked.value.includes(i.id))) {
        return false
    } else {
        return true
    }
})

//搜索结果
const searchOutcome = computed<CommonlyType[]>(() => {
    if (topRef.value) {
        topRef.value.scrollTo({
            top: 0,
            left: 0,
            behavior: 'smooth',
        })
    }

    if (inputSearch.value) {
        return list.value.flatMap((item: ContactItemType) => item.children || [])
            .filter((i: CommonlyType) => i.name.includes(inputSearch.value));
    } else {
        return []
    }
})

const topRef = ref<any>(null)

//input框搜索值
const inputSearch = ref('')

//常用列表单选
const radioChecked = ref('')

// const starColor = ref('#000')

const indexList = ref<string[]>([])

//常用列表多选
const contactsChecked = ref<string[]>([])

//列表初始化数据
const list = ref<ContactItemType[]>([])

//常用列表初始化数据
const contactsListData = ref<CommonlyType[]>([])

//打开弹窗
const openChange = () => {
    radioChecked.value = prop.commonlyId || ''

    contactsChecked.value = prop.commonlyListId || []

    getList()
}

//获取通讯录列表
const getList = async () => {
    const res: any = await getContactsList({ action: prop.parameter, operate_type: prop.operate_type, customer_id: prop.customer_id, ticket_number: prop.ticket_number })

    indexList.value = res.data.users?.map((item: ContactItemType) => item.name) || []

    indexList.value.unshift('☆')

    list.value = res.data.users || []

    contactsListData.value = res.data.favorites || []
}

//设为常用，取消常用
const cancelUsed = async (type: string) => {

    let checkIds = ''

    // add:设为常用    remove:取消常用
    if (prop.parameter === 'cc') {
        checkIds = contactsChecked.value.join(',')
    } else {
        checkIds = radioChecked.value
    }

    const res: any = await contactsAddSave({ ids: checkIds, action: type })

    if (res.statusCode === 200) {
        getList()

        showSuccessToast(type === 'add' ? '设为常用联系人成功' : '取消常用联系人成功');
    }
}

//确定
const handleConfirm = () => {

    if (prop.parameter === 'cc') {
        //多选
        const listCheckbox: CommonlyType[] = list.value
            .flatMap((item: ContactItemType) => item.children || [])
            .concat(contactsListData.value)
            .filter((item: CommonlyType) => contactsChecked.value.includes(item.id))
            .filter((value, index, self) =>
                index === self.findIndex((t) => (
                    t.id === value.id
                ))
            );

        // const listCheckbox: CommonlyType[] = [
        //     ...new Map(
        //         // 将所有符合条件的项转换成 Map，key 是 id，value 是对应的项
        //         [...list.value.flatMap((item: ContactItemType) => item.children || []), ...contactsListData.value]
        //             .filter((item: CommonlyType) => contactsChecked.value.includes(item.id))
        //             .map((item: CommonlyType) => [item.id, item]) // 转为 id 对应项的数组
        //     ).values()// 获取 Map 中的值
        // ];

        emit('checkboxChange', listCheckbox)
    } else {
        //单选
        let dataObj: CommonlyType = { id: '', name: '', username: '' };

        // 查找常用列表单选
        const commonly: CommonlyType | undefined = contactsListData.value.find((item: CommonlyType) => item.id === radioChecked.value);

        // 查找列表单选
        const commonlyList: CommonlyType | undefined = list.value
            .flatMap((item: ContactItemType) => item.children || [])
            .find((child: CommonlyType) => child.id === radioChecked.value);

        dataObj = commonly || commonlyList || dataObj;

        emit('radioChange', dataObj)

    }

    visible.value = false;

    inputSearch.value = ''

    radioChecked.value = ''

    contactsChecked.value = []
}

//关闭弹窗
const handleClose = () => {
    visible.value = false;

    inputSearch.value = ''

    radioChecked.value = ''

    contactsChecked.value = []
}

//清空搜索
const clearSearch = () => {
    inputSearch.value = ''
}

//点击右侧索引栏
const handleSelect = (value: string) => {

    // 获取索引列表
    const allLabel = document.querySelectorAll(".van-index-bar__index");

    // 获取当前索引
    const activeIndex = indexList.value.findIndex((item: string) => item == value);

    // 确保索引有效
    if (activeIndex !== -1 && allLabel[activeIndex]) {
        // 先移除已激活的项
        const activeItem = document.querySelector(".van-index-bar__index--active");

        if (activeItem) {
            activeItem.classList.remove("van-index-bar__index--active");
        }

        // 添加激活类
        allLabel[activeIndex].classList.add("van-index-bar__index--active");
    }
}

</script>

<style lang="scss" scoped>
.dialogDiv-top {
    width: 100%;
    height: 40px;
    border-bottom: 1px solid #eee;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .dialogDiv-top-left {
        display: flex;
        align-items: center;
        cursor: pointer;

        .dialogDiv-size {
            font-size: 14px;
            border: 0;
        }

        .dialogDiv-color {
            color: #1989fa;
            background: none;

        }

        :deep(.van-button, .van-button.is-round) {
            padding: 10px;
        }
    }
}

.dialogDiv-search {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    z-index: 3;
    position: sticky;
}

.clearable-used {
    width: 100%;
    margin-bottom: 10px;
    height: auto;
    z-index: 9999;

    .clearable-used-list {
        height: 30px;
        line-height: 30px;
        padding-left: 12px;
        font-size: 15px;
        background: rgb(238, 238, 238);
    }

    .clearable-used-checkbox {
        margin-left: 15px;
    }

    .clearable-used-radio {
        margin-left: 15px;
        margin-top: 15px;

    }
}

.van-list {
    height: calc(100vh - 90px);
    overflow-y: scroll;

    .checkbox-name {
        width: 300px;
        word-wrap: break-word;
    }

    &::-webkit-scrollbar {
        display: none;
    }
}
</style>